<template>
    <div style="padding:30px;">
        <el-alert :closable="false" title="">
            <transition name="fade-transform" mode="out-in">
                <template>
                    <div>
                        <upload-excel-component v-if="isShow" :on-success="handleSuccess"
                            :before-upload="beforeUpload" />
                        <EditButton @add="onAdd" @refresh="onRefresh" :listData="getList" :filterFieldName="getFields"
                            @search="onSearch"></EditButton>
                        <el-table v-loading="listLoading" :data="list" :height="iHeight" style="width: 100%">
                            <!-- <el-table-column prop="staffId" label="ID">
                            </el-table-column> -->
                            <el-table-column prop="staffCode" label="医生编号">
                            </el-table-column>
                            <el-table-column prop="staffName" label="医生姓名">
                            </el-table-column>
                            <el-table-column prop="title" label="医生职称">
                            </el-table-column>
                            <el-table-column prop="loginCode" label="登录编码">
                            </el-table-column>
                            <el-table-column fixed="right" label="操作" width="150">
                                <template slot-scope="scope">
                                    <EditTableButton @click-button="handleClick" :data="scope.row"></EditTableButton>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                            :current-page="currentPage" :page-sizes="[10, 20, 30, 40, 50, 100]" :page-size="pageSize"
                            layout="total, sizes, prev, pager, next, jumper" :total="totalSize">
                        </el-pagination>
                        <edit-form @sendUpdate="update" ref="editForm"></edit-form>
                    </div>
                </template>
            </transition>
        </el-alert>
    </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import EditForm from "@/views/common/edit-form.vue"
import { FormDataUtils, TouchType } from '@/views/common/data/ICommon';
import EditTableButton from "@/views/common/edit-table-button.vue"
import EditButton from "@/views/common/edit-button.vue"
import { IDoctorModel } from '@/api/types';
import { DoctorsModule } from '@/store/modules/doctor';
import UploadExcelComponent from '@/components/UploadExcel/index.vue'

@Component({
    name: 'Room',
    components: {
        EditForm,
        EditTableButton,
        EditButton,
        UploadExcelComponent,
    }
})
export default class extends Vue {
    public allList: Array<IDoctorModel> = []
    public list: Array<IDoctorModel> = []
    public listLoading: boolean = false
    scope: any;
    $refs: any;
    public optType: string = ""
    public isShow = false;
    public iHeight = window.innerHeight - 300;

    public currentPage: number = 1;
    public pageSize: number = 10;
    public totalSize: number = 0;

    created() {
        this.init()
    }

    public getList() {
        return this.allList;
    }
    public getFields() {
        return "title,staffName,jobCategory"
    }

    public setShowList() {
        let startIndex = this.pageSize * (this.currentPage - 1);
        this.list = this.allList.filter((value, index) => {
            return index >= startIndex && index < startIndex + this.pageSize;
        });
    }

    //操作相关处理
    public handleClick(type: TouchType, row: any) {
        if (type === TouchType.DELETE) {
            DoctorsModule.deleteDoctors(row.staffId).then(v => {
                if (v) {
                    this.list = this.list.filter(value => {
                        return value.staffId != row.staffId
                    })
                }
            });
            return;
        }
        this.optType = type;
        if (type === TouchType.SEE || type === TouchType.EDIT) {
            let keys = Object.keys(row)
            let data = FormDataUtils.getForms(row, "doctors", (key: string) => {
                return this.$t(key);
            }, type === TouchType.SEE ? keys : [], ["staffId"])
            this.$refs.editForm.showForm(data, type === TouchType.EDIT)
        } else if (type === TouchType.ADD) {
            let mod: IDoctorModel = {
                staffId: "",
                staffCode: "",
                sex: "",
                staffName: "",
                title: "",
            }
            let data = FormDataUtils.getForms(mod, "doctors", (key: string) => {
                return this.$t(key);
            }, [], [])
            this.$refs.editForm.showForm(data, true)
        }
    }

    //更新成功
    public update(obj: any) {
        console.error(obj, this.optType);
        if (this.optType === TouchType.ADD) {
            DoctorsModule.insertDoctors(obj).then(v => {
                console.error(v)
                if (v === 1) {//成功了
                    this.list.push(obj);
                }
            }).catch(ex => {
                console.error(ex);
            })
            return;
        }
        DoctorsModule.updateDoctors(obj).then(v => {
            console.error(v)
            if (v === 1) {//成功了
                for (let i = 0; i < this.list.length; i++) {
                    if (this.list[i].staffId === obj.staffId) {
                        this.list[i].staffCode = obj.staffCode;
                        this.list[i].staffName = obj.staffName;
                        this.list[i].sex = obj.sex;
                        this.list[i].education = obj.education;
                        this.list[i].nation = obj.nation;
                        this.list[i].graduationSchool = obj.graduationSchool;
                        this.list[i].status = obj.status;
                        this.list[i].jobCategory = obj.jobCategory;
                        this.list[i].politicalStatus = obj.politicalStatus;
                        this.list[i].phoneNumber = obj.phoneNumber;
                        this.list[i].officePhone = obj.officePhone;
                        this.list[i].managerialPosition = obj.managerialPosition;
                        this.list[i].title = obj.title;
                        this.list[i].academicDegree = obj.academicDegree;
                        this.list[i].majorStudied = obj.majorStudied;
                        this.list[i].loginCode = obj.loginCode;
                        this.list[i].nativePlace = obj.nativePlace;
                        this.list[i].appointmentOfPosts = obj.appointmentOfPosts;
                        break;
                    }
                }
            } else if (!obj.staffId && v) {
                obj.staffId = v;
                this.list.push(obj);
            }
        }).catch(ex => {
            console.error(ex);
        })
    }

    public onAdd() {
        this.handleClick(TouchType.ADD, null);
    }

    public onRefresh() {
        console.error("onClick onRefresh");
        this.isShow = true;
    }

    public onSearch(val: any) {
        this.list = val;
    }

    public async init() {
        this.list = [];
        this.listLoading = true
        let result: any = await DoctorsModule.getDoctors();
        this.list = result
        this.allList = result
        this.totalSize=this.allList.length;
        this.setShowList();
        setTimeout(() => {
            this.listLoading = false
        }, 0.5 * 1000)
    }

    public handleSizeChange(val: number) {
        console.log(`每页 ${val} 条`);
        this.pageSize = val;
        this.setShowList();
    }
    public handleCurrentChange(val: number) {
        console.log(`当前页: ${val}`);
        this.currentPage = val;
        this.setShowList();
    }

    public beforeUpload(file: File) {
        const isLt5M = file.size / 1024 / 1024 < 5
        if (isLt5M) {
            return true
        }
        this.$message({
            message: 'Please do not upload files larger than 1m in size.',
            type: 'warning'
        })
        return true
    }

    public async handleSuccess({ results, header }: { results: any, header: string[] }) {
        console.error(results)
        DoctorsModule.batchSaveDoctors(results)
    }
}
</script>